

Learning Go – Miniblog #10 – HTTP Servers | Late Developer
source link: https://latedev.wordpress.com/2013/01/22/learning-go-miniblog-10-http-servers/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Learning Go – Miniblog #10 – HTTP Servers
This carries on from here, and started here.
OK, time to look at how to write the HTTP server piece of the project. A quick trawl through the package documentation reveals that the library does indeed provide an HTTP server implementation, but as usual the documentation is extremely terse, and the few examples are nor all that good. Better is this article in the documentation tree. Adapting the code in the article, I came up with this:
package main import ( "fmt" "net/http" ) func csvHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "CSV stuff [%s]", r.URL.Path[5:]) } func main() { http.HandleFunc("/csv/", csvHandler) http.ListenAndServe(":8080", nil) }
This uses the default HTTP server implementation (called http), and says that any URLs that begin with /csv/ should be handled by the csvHandler function. For the moment, I just print out the remainder of the URL path after the /csv/ string. It then starts listening for requests on port 8080.
I now need to decide what kind of URLs I’m going to support. A bit of thought came up with this scheme; this specific URL /csv/index will display an index of the CSV files that I’m going to serve, where the names of the files will be hyperlinks using the second type of URL, which will look like /csv/data/filename.csv. OK, lets see if I can get that working…
Recommend
-
29
Go's built-in net/http package is convenient, solid and performant, making it easy to write production-grade web servers. To be performant, net/http automatically employs concurrency; while this is great for high l...
-
12
Twitter Follow me at @gamozolabs on Twitter if you want notifications when new blogs come up. I also do random one-off posts for cool data that doesn’t warrant an entire blog! Let...
-
4
Learning Go – Miniblog #12 – Server Objects January 23, 2013 This carries on from
-
9
Learning Go – Miniblog #14 – Closures and Goroutines January 24, 2013 This carries on from
-
10
Learning Go – Miniblog #13 – More On Server Objects January 24, 2013 This carries on from
-
7
Learning Go – Miniblog #9 – Reading CSV January 16, 2013 This carries on from he...
-
12
Learning Go – Miniblog #11 – More HTTP January 22, 2013 This carries on from ...
-
6
Learning Go – Miniblog #8 – Unit Tests January 14, 2013 This carries on from
-
5
Learning Go – Miniblog #6 – Defer January 12, 2013 This carries on from he...
-
6
Learning Go – Miniblog #7 – Creating Packages January 13, 2013 This carries on from h...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK