
Go Web Examples - adamnemecek
https://gowebexamples.github.io/
======
StevePerkins
It seems like there are three classes of "web problems" to solve:

(1) The absolute basic "hello world" stuff at the outset. How to route URL's
to their handlers, how to render dynamic templates, how to map data structures
to and from JSON, etc.

(2) The problems that are one level up in sophistication, but still common to
nearly all web apps. How to handle authentication (username/pass, OAuth/JWT,
etc), how to manage session state or the lack thereof, juggling synchronous
blocking operations with async background ones, etc.

(3) Really advanced issues that are probably specific to your industry domain
or specific application, and aren't necessarily common to others (e.g. how to
isolate this medical data for HIPPA compliance).

I don't want to poo-poo this website, it's nice. But in my mind, the world is
already flooded with Category #1 examples. At the same time, Category #3
doesn't really lend itself to this sort of thing at all. So what the world
really needs is more Category #2 stuff.

Example: What are the patterns available for authentication, including their
advantages and drawbacks?

If you do your own authentication with usernames and passwords... then you
have to either have to pass them every time and re-auth every request, or else
store a session cookie on the client side and find some way share it across
all your server-side instances (or use a load balancer with sticky sessions).
That's material for 3 or 4 patterns right there!

If you use OAuth with JWT tokens, then you can (maybe) avoid the need to store
any session state on the server side. But how do you explicitly "logout" prior
to the JWT expiration? Another 3 or 4 patterns down this route!

Category #1 is fun and easy to write about, and a lot af that material comes
from newbies who are writing in order to teach themselves. But Category #2 is
the brick wall that people always run into in the real world... and because
you need a lot of real experience to write about that class of problems,
there's a vacuum of available material out there.

~~~
tptacek
Apart from the JWT thing (please avoid JWT if possible), I agree with this
comment 100%. Things I'd like to see in a Go web app example site:

1\. Examples of using context values to pass things selectively to handlers.

2\. An arbitrary trivial middleware example, like a specialized request
logger, just to demonstrate Go middleware.

3\. A Rails/Django-style session token done in the same middleware style.

4\. Giving requests a notion of "current user".

5\. Simplified user-visible vs. developer-visible error handling.

It's too much to ask for ORM-style database query examples, I know, but that
too would be nice.

~~~
StevePerkins
> please avoid JWT if possible

That's why this Category #2 stuff is so important. People can agree without
much controversy what "best practice" is for the Category #1 stuff, but at the
next level it's just blog posts and discussion thread comments passionately
arguing opposite statements.

I'm curious... if not JWT, then how would you approach the problem of
authenticated sessions without server-side state? (assuming you aren't
rejecting the overall premise entirely)

If you track authentication with a server-side session, then you have to
either:

(1) Setup a backing store for your session state (e.g. Redis, relational
database, proprietary app server solution, etc). Share the backing store
across all instance nodes in your server-side cluster. Tune the inevitable
performance issues and point-of-failure risks, and expect the worst if you're
using a proprietary thing (they're all terrible).

(2) Use a hardware solution. Have the load balancer always route a given
client's requests to the same server-side instance. Deal with failover
scenarios when that instance goes down, have to drain traffic every time you
want to do a deployment, etc.

JWT's ugly, but no uglier than either of those! Always on the lookout for
other recipes...

~~~
tptacek
The choice isn't "JWT" or "server-side sessions". It's client-side sessions
versus server-side sessions, and JWT is just one (bad) option among many for
client-side sessions.

'lvh and I are working on a piece about this for our clients, so I want to be
careful not to write a crappy version of it in an HN comment first. But I
think you'll find something close to a consensus on JWT/JWS/JWE/JWK among
crypto engineers of our ilk.

I guess I'd close by saying: if you were writing a Rails app, it's almost
certainly the case that you'd be better off just using
ActiveSupport::MessageEncryptor to create an encrypted token than you would be
building a shambolic equivalent of MessageEncryptor in JWT.

~~~
ownagefool
You didn't actually answer the why not JWT question there.

We're pretty heavily invested with using JWT wrapped inside OpenID Connect,
and given you garner a lot of respect on such topics, I'd really be appreciate
if you cited a source or gave us a reason. Anything would be better rather
than just appealing to a vague consensus.

~~~
tptacek
Why would my advice change because you're building something that uses JWT?

This thread, though, is about Go web applications. So I guess apropos this
thread, I'd just say we probably don't need an example of how to use JWTs in
Go. But session management, yes!

~~~
ownagefool
> Why would my advice change because you're building something that uses JWT?

I never said it would, I was simply stating my interest in your opinion on the
topic. It seems a shame that you don't seem to be willing to expand though.

------
azinman2
Fantastic. I've found previous examples hard to get into... either way too
complex, not doing enough, or not structured well. Thank you!

Update: 2 requests: http/2, and https (self-signed, with chained cert, and
mutual auth)

~~~
resist_futility
another set of examples
[https://gist.github.com/denji/12b3a568f092ab951456](https://gist.github.com/denji/12b3a568f092ab951456)

------
pkulak
Love the way that library handles websockets. Perfect example of the way Go
tends to work: no magic at all, yet it's also simple, concise and elegant.

------
Shanea93
This is great, really simple and easy to follow examples.

Would you be able to add some other examples such as interfacing with a
database or making remote network requests over http?

~~~
blackss2
If you wanna simple database utility for testing golang db conn, please check
[https://github.com/blackss2/utility/blob/master/README.md](https://github.com/blackss2/utility/blob/master/README.md)

go get github.com/blackss2/utility/convert * don't use for production

------
jhoechtl
I am currently searching for an example / skeleton in Go where I can upload a
file via the browser to the server (drag and drop added bonus). Any examples?

~~~
Spiritus
Something like this will hopefully get the point across on how to handle
"multipart/form-data" forms. It will print the content of the upload to the
server's stdout.

[https://play.golang.org/p/DiNGdl27kE](https://play.golang.org/p/DiNGdl27kE)

You can use curl to test it out (it assumes a file called "foobar.txt" is
available):

    
    
        curl -v -F upload=@foobar.txt localhost:8080/upload

------
bharani_m
I am interested in trying out Go for my next side project. Can anyone
recommend any good books/videos that can help me get started?

~~~
spraak
The Go Programming Language ([https://gopl.io](https://gopl.io)) is what I've
had at my desk the past few weeks while learning. Also whenever I get stuck I
search Github code for a term like "json.Unmarshal" to find how others have
done something. And otherwise just duckduckgo'ing "golang <search term>". Also
you'll hear a million times to check out Effective Go and The Go Tour (on the
official Golang site). Those are good but I appreciate them more now that I've
got a good foundation

~~~
smt923
This is one of the things that most stood out with me while I was learning Go,
it's just so easy to read other people's examples and just understand it
without too much hard thought

------
ilozinski
Gorilla mux is way overrated and overused. I'm not sure why it's the first
choice for so many people. There are much better alternatives such as
[https://github.com/julienschmidt/httprouter](https://github.com/julienschmidt/httprouter)
or [https://github.com/gin-gonic/gin](https://github.com/gin-gonic/gin).

~~~
Arcaire
Care to explain why it's overused in comparison to other
toolkits/frameworks/libraries? Taking in to account, of course, the target
use-cases.

------
mreithub
Has anyone of you experience with the fasthttp Go library[0]?

Does it keep its promise in terms of speed? (I assume real world code would
spend much more time in actual business logic than their examples/benchmarks
so I guess there wouldn't be as much a difference as they claim, but the idea
of zero allocations intrigues me)

[0]:
[https://github.com/valyala/fasthttp](https://github.com/valyala/fasthttp)

~~~
tscs37
The fasthttp library is good if you don't need to support corner cases of HTTP
and you don't need HTTP/2.

If that is given, yes, it's faster.

~~~
daenney
If you want HTTP/2 support Chi[0] can probably help. It's plenty snappy too.

[0]: [https://github.com/pressly/chi](https://github.com/pressly/chi)

------
petepete
These look great, thanks. I'm currently learning Go and find this kind of
example much easier to follow than documentation.

I'd like to see an example for embedding HTML templates properly. It took me
an embarrassing amount of time to get beyond 'header.html' and 'footer.html'
being separate, and I'm sure my solution isn't as elegant as it could be.

~~~
joncalhoun
Is [https://www.calhoun.io/creating-the-v-in-
mvc/](https://www.calhoun.io/creating-the-v-in-mvc/) close to what you had in
mind?

I need to do a follow-up to that with the type I use to wrap that logic, but I
am curious if this is inline with what you are looking for in the examples.

~~~
petepete
Yes, thank you. My solution was similar but less elegant; I plan on going
through your post in more depth and attempt to reimplement my code with what
I've learned.

Once again, thank you for that post.

------
my_ghola
I haven't tried Go in a while but I see a lack of error handling in the code
examples. Is that just to keep the code simple? I'd rather see examples with
best practice handling of errors. Maybe show both versions so readers can see
the difference?

------
hit8run
These guides go into the right direction. I solved many things for myself but
it would be nice to collect good practices. I had to come up with go style
design patterns for: \- Middlewares \- Authentication \- Authorization \-
Database Access \- JSON APIs \- Template organization \- Migrations \- i18n \-
Crypted Cookies \- Image uploading \- Form validation \- Asset Pipeline \- API
Versioning \- Writing libs for 3rd party services Where is the best place to
share my best practices and to discuss them with others? Via a pull request to
that repo? You know of other good sources?

------
nnd
Why would I want use Go for the backend, rather than a Python or Node.js
framework? Just looking at the syntax it strikes me how inconcise and it is.

~~~
falcolas
> Just looking at the syntax it strikes me how inconcise and it is.

And you recommend Javascript instead? Interesting.

> Why would I want use Go for the backend

Fast, built-in concurrency, enough high level concepts and structures to
support fast development, and really easy to deploy.

The last part is probably the greatest. It supports simple host-based deploys,
tiny docker container deploys, and eliminates the typical dependency conflict
problems of Python and Node.

It's also pragmatic enough to make it easy to develop in for developers across
the skill bell curve.

------
elmacho39
As always (not go specific), forms example is missing form validation. Is that
too old-fashioned?

~~~
fallenhitokiri
What kind of validation are you looking for? Simple things like "is not
empty", "maximum 8 characters"...?

Most libraries I've seen which try to do form validation always lack in
certain areas or force you to define your own validation, so I simply ended up
adding an `isValid` method to my structs.

~~~
elmacho39
I want to see a full roundtrip:

1\. define input fields in html template of choice

2\. validate form/struct/whatever and prepare errror messages per field

3\. redisplay html with field-level errors to let user correct its input

step 3. is the interesting and missing in most examples of newer webframeworks

------
amelius
> This example will show how to register a route and get the data using just
> the net/http package.

What is a "route"?

(I don't need an answer, but I think the example should explain it).

------
jchannon
Go Content Negotiation -
[https://github.com/jchannon/negotiator](https://github.com/jchannon/negotiator)

------
omginternets
Anybody have experience with Echo? [0]

[0] [https://echo.labstack.com/](https://echo.labstack.com/)

~~~
nathancahill
Yes, I use it for several microservices, running for about a year now in prod.
It's excellent.

~~~
omginternets
It seems very nice indeed.

Thanks for the feedback.

------
gempir
This is awesome. Examples are so important when learning something and I
always found it hard to get good Go web examples

~~~
sherlockgopher
This might be helpful!

Tutorial: [https://github.com/thewhitetulip/web-dev-golang-anti-
textboo...](https://github.com/thewhitetulip/web-dev-golang-anti-textbook/)

YouTube series:
[https://www.youtube.com/playlist?list=PL41psiCma00wgiTKkAZwJ...](https://www.youtube.com/playlist?list=PL41psiCma00wgiTKkAZwJiwtLTdcyEyc4)

------
tlow
Why put "<li><s>" and "</s></li>" in the html file? Given your style you
should clearly abstract this out static HTML.

Edit: update. Odd that people are upvoting and downvoting this comment.

~~~
nkozyra
Possibly because the underlying HTML is not really the point of the tutorial.

~~~
tlow
In web examples HTML is "not really the point"? Ok. I can actually accept that
as reasonable. But isn't the style of this example to abstract static HTML out
of the HTML file and generate it dynamically as needed? I'll grant that it's a
rather small issue; nonetheless, I do think the author would be best served by
said abstraction for style and consistency (to the last detail).

------
adamnemecek
Actually the link should be to
[https://gowebexamples.github.io/](https://gowebexamples.github.io/) I screwed
up when posting this lol.

~~~
dang
Ok, we changed to that from
[https://gowebexamples.github.io/templates/](https://gowebexamples.github.io/templates/).

