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
+19.2k Golang : How to run your code only once with sync.Once object
+13.9k Golang : Parsing or breaking down URL
+14.9k Golang : invalid character ',' looking for beginning of value
+4.3k Golang : How to pass data between controllers with JSON Web Token
+5.5k Golang : Compound interest over time example
+5.8k Javascript : Generate random key with specific length
+18.7k Golang : Check if directory exist and create if does not exist
+22.9k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+13.6k Golang : How to pass map to html template and access the map's elements
+7.5k Golang : Handle Palindrome string with case sensitivity and unicode
+6.2k Golang : When to use make or new?