Golang : HTTP Server Example
Simple tutorial on HTTP server examples with Golang. Run the codes below and point your browser to http://localhost:8080
or http://localhost:8080/replyname/yourname
for example 2.
Example 1:
package main
import (
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", mux)
}
Example 2:
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.4k Golang : Convert IP version 6 address to integer or decimal number
+7k Golang: Prevent over writing file with md5 hash
+7.3k Golang : Executing and evaluating nested loop in html template
+3.2k Java : Generate multiplication table example
+18.9k Golang : How to read float value from standard input ?
+10.3k Golang : Simple client-server HMAC authentication without SSL example
+8.9k Golang : Convert file unix timestamp to UTC time example
+5.1k CodeIgniter : form input set_value cause " to become & quot
+7.7k Golang : Play .WAV file from command line
+4.6k Golang : Struct field tags and what is their purpose?
+24.6k Golang : Calculate future date with time.Add() function
+13.2k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name