DEV Community

Tawhid
Tawhid

Posted on • Updated on

How to make a simple webserver in GO Lang

Today,In this blog we will build a simple webserver in GO Lang to serve static files.
Go is often called the C of 20th century.Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.

If you are completely new in GO,Don't worry you can understand this tutorial and catch along and comment if you want a complete GO tutorial.

Full code in my Github
First Install go

Here

Create a new go project

so in create a folder create a static folder and a main go file on the root directory.In the static folder create form and index html files.

So the hiearchy looks like:

-static
---index.html
---form.html
-main.go

after that let's get into the main go file.
so first we will declare the file as main package.
The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program. When you build shared libraries, you will not have any main package and main function in the package.
Then we will import format package,log lib anf net/http module.
so it will look like:

package main

import(
    "fmt",
    "log",
    "net/http",
)
Enter fullscreen mode Exit fullscreen mode
package main


import(
    "fmt",
    "log",
    "net/http",
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, world!")
}


func main(){

    fileserver = http.FileServer(http.Dir("./static"))
    http.Handle("/", fileserver)
    http.HandleFunc("/form", formHandler)
    http.HandleFunc("/hello", helloHandler)
//listen and serve
    fmt.Println("Listening... at port 5500\n")
    if error := http.ListenAndServe(":5500", nil); error != nil {
        log.Fatal(error)
    }


}
Enter fullscreen mode Exit fullscreen mode

then we will declare main function with func keyword.Then tell go where is the static files then handle http request of /form.we will later need it bc we will call it from our html.Then the same but for hello world.Then make the server listen to port 5500 and if there is any errors print it.Then we will create a hello handler function which will take two parameters, one response another request.
After that we will set error listeners for http not found and method not allowed.
We can listen at port 5500 with

 http.ListenAndServe(":5500", nil)
//with error logging
    fmt.Printf("Starting server at port 5500\n")
    if err := http.ListenAndServe(":5500", nil); err != nil {
        log.Fatal(err)
    }
Enter fullscreen mode Exit fullscreen mode

this must be called from main function.

func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/hello" {
        http.Error(w, "404 not found", http.StatusNotFound)
        return
    }
    if r.Method != "GET" {
        http.Error(w, "method is not supported", http.StatusNotFound)
        return
    }
    fmt.Fprintf(w, "hello!")
}

Enter fullscreen mode Exit fullscreen mode

we can access value with name := r.FormValue("name") and print form input value with fmt.Fprintf(w, "Name = %s\n", name)

we can print error with a if loop looking for probs while parsing the value.
which is

    if err := r.ParseForm(); err != nil {
        fmt.Fprintf(w, "ParseForm() err: %v", err)
        return
    }
Enter fullscreen mode Exit fullscreen mode

Now that we are done with server file lets write some basic html

Index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index page</title>
    <!--Bootstrap cdn-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!--Font awesome cdn-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

</head>
<body>
<a class="btn btn-secondary" href="form.html">Form</a>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

form.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FORM</title>
    <!--Bootstrap cdn-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!--Font awesome cdn-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
       <!--Bootstrap input-->
       <form method="POST" action="/form">
       <input type="text" class="form-control" placeholder="Name" name="name" value="" required>
       <input type="text" class="form-control" placeholder="Address" name="address" value="" required>
 <input type="submit" class="btn btn-success" value="Submit">
</form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

run the go compiler to run/build your file and use the html locally and hopefully everything will work.
Buy me a coffee

Discussion (0)