Runtime error: invalid memory address or nil pointer dereference #1

Displays what?

@radovskyb THIS :

     s test
    %!(EXTRA []uint8=[73 32 97 109 32 111 110 32 105 115 67 111 110 113 117 101 115 116 10])

Did you replace the fmt.Println in viewHandler with:

fmt.Fprintf(w, "%s%s", p.Title, p.Body)

or did you replace it with a fmt.Fprintln by mistake?

One other thing, did you keep the structure of fmt.Fprintf(w, "%s%s", p.Title, p.Body) or did you add more items to it or remove one of the %s, because %s%s will take 2 items and format them as strings, so changing it will affect the results if you either removed one of the %s or if you added something else near p.Title and p.Body.

@radovskyb Ok. It worked but on the tutorial I was given this line code :

    ` fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body`

So Is this not the correct code to use?

That code is fine, it formats 2 %s's with p.Title and p.Body.

For example, if you don’t have the correct number of items with a fmt.Printf or fmt.Fprintf, something like this:

fmt.Printf("%s\n", "Hello", []byte("World!"))

Will print this:

%!(EXTRA []uint8=[87 111 114 108 100 33])```

@iivri, once again if you haven’t already, I would still suggest going through the go tour to learn the very basics of Go, but if you are also having trouble understanding the above with the formatted printing, I also suggest that you at least skim through the following page: https://golang.org/pkg/fmt/.

@radovskyb It works with both. I have be using the Golang website to learn the language. I went through the tutorials, my issue is just application and connection of these abstract concepts. I will attempt to finish the website tutorial and if I have any issues I hope you will be willing to help as you have done graciously. I am indebted to you for your patience and welcoming attitude to my lack of understanding. lol :relaxed:

Of course, no problem. Feel free to ask any questions here anytime or even direct message me if you like and I’m always happy to help. I’m still no expert these days, but even the best programmers had to start somewhere :slight_smile:

If you’re ever stuck and need any examples for the basic functions and methods for Go's standard library, I put this repository up a while ago which can be really helpful sometimes:
https://github.com/radovskyb/go-packages.

If there’s anything missing from it that you are finding hard to learn, let me know and I’m more than happy to add more examples for the things that are missing on there.

@radovskyb I will definitely be direct messaging You lol. Incidentally I am from Jamaica, Interested in blockchains and smart contracts and how they can fix our financial sector. :grinning:

1 Like

Sounds like an interesting topic :smiley:

I hope your learning goes smoothly and nice to meet ya!

@radovskyb Hello again! How are you? Hope you are well. I have another issue with which I need assistance. So I finished the exercise and is now running the code and I got this error :

html/template: "edit .html" is undefined

THIS is how my code looks :

package main


 
import (
  "fmt"
  "io/ioutil"
  "net/http"
  "os"
  "log"
  "html/template"
  "regexp"
)

// define page as a struct with 2 fields representinG the title and body

type page struct{
   Title string
   Body []byte // byte slice  (See Slices : usage and internals )

}

// create the save method on the page struct for persistent storage

func (p *page) save() error  { // THe method will save the page's body to a text file
 isdoC := p.Title + ".txt"
 return ioutil.WriteFile(isdoC, p.Body, 0600)

}

 func loadpage(title string) (*page, error)  {
    isdoC := title + ".txt"
    body, err := ioutil.ReadFile(isdoC)
    if err != nil {
          return nil, err
   }
   return &page{Title: title, Body: body}, nil

}

func viewHandler(w http.ResponseWriter, r *http.Request,  title string)  {
p, err  := loadpage(title)
if err != nil {
    http.Redirect(w, r, "/edit/" + title, http.StatusFound)
    return

renderTemplate(w, "view", p)
}

fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body)
}

func editHandler(w http.ResponseWriter, r *http.Request,  title string)  {
 p, err := loadpage(title)
 if err != nil {
  p = &page{Title: title}
 }
 renderTemplate(w, "edit", p)

}

func saveHandler(w http.ResponseWriter, r * http.Request, title string)  {
 body := r.FormValue("body")
 p := &page{Title: title, Body: []byte(body)}
 err := p.save()
 if err != nil {
  http.Error(w, err.Error(), http.StatusInternalServerError)
  return
 }
 http.Redirect(w, r, "/view/" + title, http.StatusFound)
}
var templates = template.Must(template.ParseFiles("edit.html", "view.html"))

func renderTemplate(w http.ResponseWriter, tmpl string, p *page)  {
      err := templates.ExecuteTemplate(w, tmpl+" .html", p)
      if err != nil {
       http.Error(w, err.Error(), http.StatusInternalServerError)
      }
}

var validpath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")

func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc  {
     return func (w http.ResponseWriter, r *http.Request)  {
 
                 m := validpath.FindStringSubmatch(r.URL.Path)
                 if m == nil {
                  http.NotFound(w, r)
                  return
           }
           fn(w, r, m[2])

         }
}
func main()  {
 http.HandleFunc("/view/", makeHandler(viewHandler))
 http.HandleFunc("/edit/", makeHandler(editHandler))
 http.HandleFunc("/save/", makeHandler(viewHandler))

 http.ListenAndServe(":8080", nil)
 cwd, err := os.Getwd()
if err != nil {
	log.Fatalln(err)
}
fmt.Println(cwd)
}

I am not seeing the error

Hey @iivri, looks like you made a simple typo in your renderTemplate function :slight_smile:

err := templates.ExecuteTemplate(w, tmpl+" .html", p)

You accidentally added an extra space.

Change " .html" to ".html" and it should be fine! :]

@radovskyb Thank You once again. Also, why was the space an issue? Is is that whitespace is that important in the construct of the Code?

Yep. In this context, tmpl+" .html" means that with the extra space it was looking for a file called edit .html instead of edit.html.

@radovskyb I really appreciate the Help. Question :

WHAT does the go install mean in this context? :

go install github.com/iivri/eloiim 

THIS is my directory path (Is this the correct term?) :

mkdir $GOPATH/src/github.com/iivri/eloiim

I was then told to build and install the program I created in the elloiim folder using this go tool : go install

WHAT does go install command do in succinct detail? :slight_smile:

Using go install compiles an executable from your code and then places the compiled file in the bin directory in your workspace.

This page can explain it a lot better than I can though: https://golang.org/doc/code.html#Command.

Ok. I read and understood it but I just wanted to get a different perspective.

@radovskyb I am testing is a package I built

Stringutil 

is compiling and I used go build to do it. THIS is the error I got :

eloiim:~ iivri.andre$ go build github.com/iivri/Stringutil
can't load package: package github.com/iivri/Stringutil: 
deedSpace/src/github.com/iivri/Stringutil/reverse.go:5:1:       expected 'package', found 'func'

WHAT am I do wrong? I think the issue is with the go build Is it still useful? Also I was instructed to use the go install if I was working with a package’s source directory but it is giving me this error :

eloiim:~ iivri.andre$ go install github.com/iivri/Stringutil 
can't load package: package github.com/iivri/Stringutil: 
deedSpace/src/github.com/iivri/Stringutil/reverse.go:6:1:   expected 'package', found 'func' 

WHICH is the same thing.

In this case the package’s source directory would be the folder in my $HOME directory?

The issue would not with using go build or go install since they are both very common to use.

I do however believe that you might have accidentally left out a package declaration in one of your files, for example:

package stringutil

is probably missing at the top of the file reverse.go.

Just as a side note, when you are having any issues following along these tutorials, whenever something doesn’t work, try to copy the tutorials code over your own code and check to make sure that everything is there and that you aren’t missing anything :slight_smile:

func reverse(s string) string  {
   r := []rune(s)
for i, j := 0, len(r)-1 < len(r)/2; i, j = i+j, j-1;  {
  r[i], r[j] = r[j], r[i]

 }
 return string(r)
}

@radovskyb THIS is the code. I copied it line for line but the error is saying expected

'package' found 'func' . THE instructions do not include that

ā€˜package’ declaration however. So I am a bit confused, I am assuming that if package was necessary then the instructions would have said that.