-3

https://youtu.be/ASBUp7stqjo am making the server from this video and it shows the following error in the code unexpected semicolon or newline before { ( syntax [Line 10 Col 1] ) here is the golang code

there is also 2 html code files which can be found in the video but the Problem is arising in func main() so i posted only the Go Code

package main 

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

func main() 
{
    fileServer := http.FileServer(http.Dir("./static"))
    http.Handle("/", fileServer)
    http.HandleFunc("/form", formHandler)
    http.HandleFunc("/hello", helloHandler)

    fmt.Printf("Starting Server at port 8080\n")

    if err := http.ListenAndServe(8080, nil); err != nil {
        log.Fatal(err)
    }
}

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, "404 not found", http.StatusNotFound)
    return
    }

    fmt.Fprintf(w, "hello!")
}

func formHandler(w http.ResponseWriter, r *http.Request) {

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

    fmt.Fprintf(w, "POST request successful")
    name := r.FormValue("name")
    address := r.FormValue("address")
    

    fmt.Fprintf(w, "Name = %s\n", name)
    fmt.Fprintf(w, "Address = %s\n", address)

}


i wanted to make a wbe server from the video and it shows a semicolon syntax error

CodeX-HH
  • 9
  • 1
  • 4
    Remove the line break after `func main()`. – Peter Apr 07 '23 at 11:33
  • Also see [How to break a long line of code in Golang?](https://stackoverflow.com/questions/34846848/how-to-break-a-long-line-of-code-in-golang/34848928#34848928) – icza Apr 07 '23 at 12:13
  • `if err != r.ParseForm(); err != nil {` is wrong. Replace the first of the `!=` with `:=`. – Tinkerer Apr 07 '23 at 13:14

1 Answers1

1

Use gofmt command, with that you will be able to easily identify any syntax error.

Another solution is just to paste your code to https://go.dev/play/, and click format. Any line of code that contains syntax errors will be highlighted in red.


Now back to your code, there are two problems that I can see:

1st problem

Change

func main() 
{

to

func main() {

2nd problem

Change

if err := http.ListenAndServe(8080, nil); err != nil {

to

if err := http.ListenAndServe(":8080", nil); err != nil {
novalagung
  • 10,905
  • 4
  • 58
  • 82