Feedback Welcome: 'Shorten your URL'

To practice my Go skills, I’ve implemented a simple web application that allows you to shorten an URL. The application consists of a backend written in Go and a web frontend using jQuery with some plugins and Bootstrap for layout.

The code is available on GitHub at https://github.com/lutzhorn/shorturl, the application is deployed on https://u.lhorn.de.

I would very much appreciate any feedback you can give especially on the Go part. Coming from a Java and Python background, I’m trying to get into the Go way of programming, In Python there is a ‘Pythonic’ way to write code, I am sure there is something similar in Go: File structure, name choice, exporting names, error handling, …

If you have a little time, please tak a look at the code, play with the deployed application, and please give me feedback.

Thanks!

I took a look at the code. Here are my initial impressions.

Config

Too much config data is passed to NewURLDB. From its name, I expected it would only access Config.Db, but it also accesses Config.Hashids and could (but does not seem to) access Config.Views and Config.HTTP.

Simplify handler registration

http.HandleFunc("/index.html", func(w http.ResponseWriter, req *http.Request) {
	func(handler *Handler) {
		handler.Index(w, req)
	}(handler)
})
http.HandleFunc("/js/index.js", func(w http.ResponseWriter, req *http.Request) {
	func(handler *Handler) {
		handler.IndexJS(w, req)
	}(handler)
})
http.HandleFunc("/css/index.css", func(w http.ResponseWriter, req *http.Request) {
	func(handler *Handler) {
		handler.IndexCSS(w, req)
	}(handler)
})
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	func(handler *Handler) {
		handler.Root(w, req)
	}(handler)
})

Can be simplified to:

http.HandleFunc("/index.html", handler.Index)
http.HandleFunc("/js/index.js", handler.IndexJS)
http.HandleFunc("/css/index.css", handler.IndexCSS)
http.HandleFunc("/", handler.Root)

HTTP Errors

Instead of:

io.WriteString(w, "Internal Server Error")
w.WriteHeader(http.StatusInternalServerError)

Write:

http.Error(w, "Internal Server Error", http.StatusInternalServerError)
2 Likes

Yes, there is. It is called “idiomatic Go”. Two starting points:

When in Go, do as Gophers do

Idiomatic Go

And of course, Effective Go from the Go docs.

1 Like

@nathankerr, @christophberger Thanks for the suggestions and the links. I will change the handler registration to this much shorter form.

There are also responses here: https://groups.google.com/d/topic/golang-nuts/FhAypQQomZU/discussion

Indeed, I’ve crossposted this question :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.