Distinguish path and filepath
Distinguish path and filepath
Use path for slash-separated logical names, such as URL path components (not entire URLs). Use path/filepath for native filesystem paths. Joining and cleaning are string operations; they do not access the filesystem or prove a destination is safe.
package main
import ( "fmt" "path")
func main() { p := path.Join("/docs", "go", "..", "index.html") fmt.Println(p, path.Base(p), path.Ext(p))}Join combines elements and cleans the result. Base selects the last component; Ext returns the final suffix including the dot. Use net/url for URL parsing and escaping. A cleaned string can still point outside a desired directory.
Expected output:
/docs/index.html index.html .htmlNative paths
package main
import ( "fmt" "path/filepath")
func main() { p := filepath.Join("docs", "go", "readme.txt") fmt.Println(filepath.ToSlash(p)) fmt.Println(filepath.Base(p), filepath.Ext(p)) r, e := filepath.Rel("docs", p) fmt.Println(filepath.ToSlash(r), e == nil)}filepath.ToSlash converts the native separator to slash for display. Rel computes a relative path lexically and may return an error. It can produce .. components; it is not a security boundary.
Expected output:
docs/go/readme.txtreadme.txt .txtgo/readme.txt trueTry it locally
Join "assets" and "logo.png" with filepath.Join, print the slash form and extension.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 03: Distinguish path and filepath
Check the lesson objective before moving on.
Which package joins native disk paths?
Does Clean resolve symlinks?