top | item 13612941

Go Web Examples

357 points| adamnemecek | 9 years ago |gowebexamples.github.io | reply

90 comments

order
[+] StevePerkins|9 years ago|reply
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|9 years ago|reply
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.

[+] azinman2|9 years ago|reply
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)

[+] pkulak|9 years ago|reply
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|9 years ago|reply
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?

[+] jhoechtl|9 years ago|reply
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|9 years ago|reply
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

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

    curl -v -F [email protected] localhost:8080/upload
[+] merlish|9 years ago|reply
I actually wrote an extremely shonky/basic file upload thing and contributed it to the weird 'illacceptanything' repository, while that was a thing, about a year and a half ago.

Maybe you'll find it helpful, maybe not. Ignore the bindata.go stuff and look at main.go (inc. file accepting) & the file upload control (w/Bootstrap fileinput.min.js) & the braindead simple HTML templating stuff.

https://github.com/leafi/illacceptanything/commit/1b78922f89...

[+] lesiki|9 years ago|reply
I don't know much about Go so can't speak to the server-side handling of file uploads. The drag/drop side of things is server agnostic - I strongly recommend http://www.dropzonejs.com
[+] lentil|9 years ago|reply
This might be more of a complete app than you need, but https://transfer.sh is open source and it looks fairly compact. Could be some interesting examples in there?
[+] bitexploder|9 years ago|reply
I really like the gophish app for easy to understand common patterns in web apps.
[+] bharani_m|9 years ago|reply
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?
[+] wwalser|9 years ago|reply
This is how I got started: https://tour.golang.org/welcome/1

Work through those followed by a few project Euler challenges then implement something simple in the domain that you normally work in. For me that's web so I implemented a little HipChat bot.

[+] spraak|9 years ago|reply
The Go Programming Language (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
[+] beliu|9 years ago|reply
Another great resource for getting started is https://gobyexample.com/.

Also check out usage examples on Sourcegraph (disclaimer: I'm the CTO). We sell our tool to companies to use on their private code, but a side effect is that we've indexed usage examples for just about every popular Go open-source library. For example,

- Go std lib http package: https://sourcegraph.com/github.com/golang/go@bb41b4d599f5758...

- Popular gorilla/mux routing library: https://sourcegraph.com/github.com/gorilla/mux@34bf6dc9faa08...

- Gorp, a popular ORM-ish library: https://sourcegraph.com/github.com/go-gorp/gorp@033bf796a22f...

Cross-repo jump-to-def + find-references = great for making sense of new code.

[+] joncalhoun|9 years ago|reply
If you want to ping me with what you are looking to build and your programming experience level I can recommend more specific resources. jon [at] calhoun.io

Many resources (like my book) are targeting absolute beginners so they are a bit lengthier to read if you are experienced, whereas other great books and whatnot are really hard for beginners to follow so at least expressing your skill level would help me recommend specific resources.

[+] adamnemecek|9 years ago|reply
I know this isn't a book but if you need a go development environment, cloud9 (https://c9.io) ended up being a surprisingly productive environment. Like for go development, it's been better than anything I've tried to setup locally and the IDE even has go autocomplete.
[+] weberc2|9 years ago|reply
In particular, if you have any problems, /r/golang is very helpful. They'll help get you unstuck quickly.
[+] mreithub|9 years ago|reply
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

[+] tscs37|9 years ago|reply
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.

[+] sagichmal|9 years ago|reply
I don't recommend it; it doesn't actually implement HTTP, and the stdlib package net/http is extremely fast on its own.
[+] petepete|9 years ago|reply
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.

[+] my_ghola|9 years ago|reply
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|9 years ago|reply
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|9 years ago|reply
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|9 years ago|reply
> 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.

[+] simplyluke|9 years ago|reply
In general: more performant, much better at threading through goroutines. It's worth noting go is compiled, so it's more comparable to a language like C++ than a dynamic language like python or JS.
[+] elmacho39|9 years ago|reply
As always (not go specific), forms example is missing form validation. Is that too old-fashioned?
[+] amelius|9 years ago|reply
> 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).

[+] tlow|9 years ago|reply
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|9 years ago|reply
Possibly because the underlying HTML is not really the point of the tutorial.